import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getJWTExpireTime } from '@/utils/index'
import { getAccessToken } from './auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // hack
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.accessToken) {
      const exp = getJWTExpireTime(store.getters.accessToken)
      // console.log('url:' + config.url + ',请求时间:' + new Date())
      if (exp * 1000 < new Date().getTime()) {
        // 如果没有在刷新token，则刷新
        MessageBox.alert('登录过期，请重新登录', '提示', {
          confirmButtonText: '重新登录',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      config.headers.accessToken = getAccessToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.dir(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    console.log(response)
    if (response.status !== 200 || response.data.code !== 0) {
      // if (response.status === 401) {
      // }
      console.log('出错了:' + response.data.msg)
      return Promise.reject(new Error(response.data.msg || 'Error'))
    } else {
      return response.data
    }
  },
  error => {
    console.dir(error) // for debug
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

